/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.google.collabframework.texteditor.server;

import com.google.collabframework.texteditor.model.Document;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.concurrent.Semaphore;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author robert
 */
public class DocServer extends UnicastRemoteObject implements IDocServer {

    private Document doc;
    private Semaphore s;

    public DocServer() throws RemoteException {
        super();
        doc = new Document("ich bin ein test\nWeil ich sehen will, wie es funktioniert!");
        s = new Semaphore(1);

    }

    public void add(int line, int column, char c) throws RemoteException {
        try {
            System.out.println(doc.toString());
            s.acquire();
            doc.add(line, column, c);
            s.release();
            System.out.println(doc.toString());
        } catch (InterruptedException ex) {
            Logger.getLogger(DocServer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void remove(int line, int column) throws RemoteException {
        try {
            System.out.println(doc.toString());
            s.acquire();
            doc.remove(line, column);
            s.release();
            System.out.println(doc.toString());
        } catch (InterruptedException ex) {
            Logger.getLogger(DocServer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public String getText() throws RemoteException {
        return doc.toString();
    }

    public int size(int i) throws RemoteException {
        return doc.getSize(i);
    }

    public int lineCount() throws RemoteException {
        return doc.getLineCount();
    }

    public static void main(String[] args) {
        try {
            try {
                Naming.rebind("DocServer", new DocServer());
            } catch (MalformedURLException ex) {
                Logger.getLogger(DocServer.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (RemoteException ex) {
            Logger.getLogger(DocServer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
